// Initialize your app

var cinemainfourl = '/cinemainfo';
var collectioncinemainfourl = '/collectioncinemainfo';
var footprintcinemainfourl = '/footprintcinemainfo';
var collectionmovieinfourl = '/collectionmovieinfo';
var footprintmovieinfourl = '/footprintmovieinfo';
var getCityByPostionurl = '/getCityByPostion';
var updatecinemacollectionurl = '/updatecinemacollection';
var updatemoviecollectionurl = '/updatemoviecollection';
var sharemoviedetail = '/sharemoviedetail';
var sharecinemadetail = '/sharecinemadetail'

var myApp = new Framework7({
    init: false, //Disable App's automatica initialization
    // Default title for modals
    modalTitle: '提示',
    modalButtonOk: '确认',
    modalButtonCancel: '取消',
    pushState: true,
    swipeBackPage: false,
    uniqueHistory: true,
    showBarsOnPageScrollEnd: false,
    swipePanelOnlyClose: 'right',
    imagesLazyLoadPlaceholder: "http://cdn.bestmovie.com.cn/wechat/img/resource-loading.gif",
    activeStateElemets: 'a, button',
    // Hide and show indicator during ajax requests
    onAjaxStart: function (xhr) {
        myApp.showIndicator();
    },
    onAjaxComplete: function (xhr) {
        myApp.hideIndicator();
    },
    onPageBack: function (app, page) {
        //关闭已打开的右侧窗
        myApp.closePanel('right');
        //关闭pop弹层
        myApp.closeModal();
    },
    onPageInit: function (app, page) {
        if (myApp.getCurrentView().activePage.name == 'cinemadetail') {
            var opt = {
                title: $$(page.container).find('.cinemaname').text(), // 分享标题
                desc: $$(page.container).find('.comment').text(),//分享描述
                link: window.location.host + sharecinemadetail + window.location.href.substring(window.location.href.lastIndexOf('?')), // 分享链接
                imgUrl: $$(page.container).find('.picture img').data('src'), // 分享图标
                success: function () {
                },
                cancel: function () {
                }
            }
            wx.onMenuShareAppMessage(opt);
            wx.onMenuShareTimeline(opt);
            wx.onMenuShareQQ(opt);
            wx.onMenuShareQZone(opt);
            wx.showOptionMenu();
        } else if (myApp.getCurrentView().activePage.name == 'moviedetail' || myApp.getCurrentView().activePage.name == 'moviesearchdetail') {
            var opt = {
                title: $$(page.container).find('.moviename').text(), // 分享标题
                desc: $$(page.container).find('p.detail').text(),
                link: window.location.host + sharemoviedetail + window.location.href.substring(window.location.href.lastIndexOf('?')), // 分享链接
                imgUrl: $$(page.container).find('.picture img').data('src'), // 分享图标
                success: function () {
                },
                cancel: function () {
                }
            }
            wx.onMenuShareAppMessage();
            wx.onMenuShareAppMessage(opt);
            wx.onMenuShareTimeline(opt);
            wx.onMenuShareQQ(opt);
            wx.onMenuShareQZone(opt);
            wx.showOptionMenu();
        } else {
            wx.hideOptionMenu();
        }

    }

});

Template7.registerHelper('jsonDecodeNumbers', function (s) {
    return JSON.parse(s).numbers;
});
Template7.registerHelper('jsonDecodeContact', function (s) {
    return JSON.parse(s).bookingContact;
});
Template7.registerHelper('jsonDecodeComment', function (s) {
    return JSON.parse(s).userComment;
});
Template7.registerHelper('formatChineseWeek',function (w) {
    var cWeek = '';
    if (w == 1){
        cWeek = '周日';
    } else if (w == 2){
        cWeek = '周一';
    } else if (w == 3){
        cWeek = '周二';
    } else if (w == 4){
        cWeek = '周三';
    } else if (w == 5){
        cWeek = '周四';
    } else if (w == 6){
        cWeek = '周五';
    } else {
        cWeek = '周六';
    }
    return cWeek;
});

Template7.registerHelper('formatPrice', function (money) {

    if(money==""){
        return "";
    }
    if(money){
        money = parseInt(money)*0.01;
    }
    if(/[^0-9\.\-\+]/.test(money)){
        return money;
    }
    money = parseFloat(money) + "";
    if('NaN' == money){
        return  "0.00";
    }
    var money_flag = "";
    if(money.indexOf("-") != -1){
        money = money.replace(/-/g,"");
        money_flag = "-";
    }
    money=money.replace(/^(\d*)$/,"$1.");
    money=(money+"00").replace(/(\d*\.\d\d)\d*/,"$1");
    money=money.replace(".",",");
    var re=/(\d)(\d{3},)/;
    while(re.test(money)){
        money=money.replace(re,"$1,$2");
    }
    money=money.replace(/,(\d\d)$/,".$1");
    var money =  money_flag+""+money.replace(/^\./,"0.")
    return money;

    // num = num * 0.01;
    // num += '';
    // var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
    // num = num.replace(reg, '$1,');
    // return num;
});

Template7.registerHelper('CND',function (url) {
    const c = 'http://cdn.bestmovie.com.cn/'
    return c + url;
})

function title(title) {
    document.title = title;
    if (!myApp.device.android) {
        var $body = $$('body');
        var $iframe = $$('<iframe src="http://cdn.bestmovie.com.cn/wechat/img/favicon.ico"></iframe>');
        $iframe.on('load', function () {
            setTimeout(function () {
                $iframe.off('load').remove();
            }, 0);
        }).appendTo($body);
    }
}

// Export selectors engine
var $$ = Dom7;

// Add view
var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
    domCache: true
});
var latitude;
var longitude;

wx.ready(function () {
    wechatConfigInit = true;

    wx.hideOptionMenu();


    wx.error(function (res) {
        // alert(res.errMsg);
        wechatConfigInit = false;
    });

});

function getLocation() {
    $$.ajax({
        url: getCityByPostionurl,
        method: 'POST',
        async: false,
        dataType: 'json',
        data: {
            lat: latitude,
            long: longitude
        },
        success: function (data, status, xhr) {
            if (data.status == 'error') {
                myApp.alert(data.message);
                $$("#locat").html('定位失败');
                return;
            }
            cityname = data.city.rows.name;
            citycode = data.city.rows.citycode;
            localStorage.setItem('cityname', cityname);
            localStorage.setItem('citycode', citycode);
            $$("#locat").html(cityname);
        }
    })
};

myApp.onPageInit('cinema', function (page) {
    title('点播院线');

    var map, geolocation;
    map = new AMap.Map('iCenter');
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,        //超过10秒后停止定位，默认：无穷大
            maximumAge: 5000
        });
        map.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        geolocation.getCurrentPosition();
    });
//解析定位结果
    function onComplete(data) {
        latitude = data.position.getLat(); // 纬度，浮点数，范围为90 ~ -90
        longitude = data.position.getLng(); // 经度，浮点数，范围为180 ~ -180。
        var param = {
            lastIndex: $$(".cinema li").length,
            citycode: localStorage.citycode,
            mid: $$(page.container).find('.searchbar-input').data('mid'),
            lat: latitude,
            long: longitude
        };
        getCinemaInfomation(cinemainfourl, param);
        if (localStorage.getItem('citycode') != '' &&
            localStorage.getItem('citycode') != null) {
            cityname = localStorage.getItem('cityname');
            citycode = localStorage.getItem('citycode');
            $$("#locat").html(cityname);
        } else {
            getLocation();
        }
    }

//解析定位错误信息
    function onError(data) {
        myApp.alert('获取地理信息失败');
        $$("#locat").html('定位失败');
        var param = {
            lastIndex: $$(".cinema li").length,
            citycode: localStorage.citycode,
            lat: latitude,
            long: longitude
        };
        getCinemaInfomation(cinemainfourl, param);
    };

    mySearchbar = myApp.searchbar('.cinemasearchbar', {
        customSearch: true,
        onSearch: function () {
            if (cinemaxhr) {
                cinemaxhr.abort();
            }
            var param = {
                lastIndex: 0,
                citycode: localStorage.citycode,
                mid: $$(page.container).find('.searchbar-input').data('mid'),
                lat: latitude,
                long: longitude,
                cinema_name: mySearchbar.query
            };
            myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.cinema-infinite-scroll'));
            $$('.cinema').html('');
            getCinemaInfomation(cinemainfourl, param);
        }
    });


    $$('.cinema-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        var param;
        param = {
            lastIndex: $$(mainView.activePage.container).find(".cinema li").length,
            citycode: localStorage.citycode,
            cinema_name: mySearchbar.query,
            mid: $$(page.container).find('.searchbar-input').data('mid'),
            lat: latitude,
            long: longitude
        }
        getCinemaInfomation(cinemainfourl, param);

    });
});


var loading = false;
var mySearchbar = null;

var tempcreate_time = '';
function setCinemaForm(cinemaData) {
    // 生成新条目的HTML
    var html = '';
    $$.each(cinemaData, function (i, v) {
        if (v["cinemaName"]) {
            if (v["create_time"] && v["create_time"] != tempcreate_time) {
                tempcreate_time = v["create_time"];
                html += '<div style="padding-left: 15px;color: #9e9e9e">' + v["create_time"] + '</div>'
            }
            html += '<li>';
            html += '<a href="cinemadetail?cinema_code=' + v["cinema_code"] + '" data-ignore-cache="true">';
            html += '<div class="item-content">';
            html += '<div class="item-media radius"><img src=';
            if (v["cinema_picture"]) {
                html += v["cinema_picture"]
            } else {
                html += "http://cdn.bestmovie.com.cn/wechat/img/1.png";
            }
            html += ' onerror=\'this.src="img/1.png"\'  width="80" height="80"></div>';
            html += '<div class="item-inner">';
            html += '<div class="item-title-row">';
            html += '<div class="item-title" style="font-size:large">' + v["cinemaName"] + '</div>';
            html += '</div>';
            html += '<div class="item-title-row" style="font-size: small;color: gray">';
            html += '<div class="item-text" style="font-size: small">' + v["cinemaAddress"] + '</div>';
            html += ' <div class="right" style="text-align:right;"><div>&nbsp;';
            if (v["distance"] != "null") {
                html += v["distance"];
            }
            html += '</div><div style=" text-align:right;">';
            if (v["score"]) {
                html += '<img style="width: 15vw;margin-top: 10px" src="http://cdn.bestmovie.com.cn/wechat/img/' + v["score"] + 'star.png" >' + '';
            }
            html += '</div></div></div></div></div></div></a></li>';
        } else {
            html += '<li></li>';
        }
    });

    $$('.cinema').append(html);
    loading = false;

};

myApp.onPageReinit('cinema', function (page) {
    title('点播院线');
    wx.hideOptionMenu();
});


// //  电影搜索部分
// myApp.onPageInit('cinemafilm', function (page) {
//     if ($$('.page-on-center').data('page') == 'cinema') {
//         cinemaInit();
//     }
// });
//
// myApp.onPageReinit('cinemafilm', function (page) {
//     title('点播院线');
// });
//

myApp.onPageInit('location', function (page) {
    title('城市选择');
    if (mySearchbar && mySearchbar.active) {
        mySearchbar.disable();
    }

    var map, geolocation;
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('iCenter');
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        });
        map.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        geolocation.getCurrentPosition();
    });
    //解析定位结果
    function onComplete(data) {
        latitude = data.position.getLat(); // 纬度，浮点数，范围为90 ~ -90
        longitude = data.position.getLng(); // 经度，浮点数，范围为180 ~ -180。
        $$.ajax({
            url: getCityByPostionurl,
            method: 'POST',
            dataType: 'json',
            data: {
                lat: latitude,
                long: longitude
            },
            success: function (data, status, xhr) {
                if (data.status == 'error') {
                    myApp.alert(data.message);
                    $$('#loc').text('定位失败');
                    return;
                }
                citycode = data.city.rows.citycode;
                $$('#loc').find('.item-title').attr('citycode', citycode);
                name = data.city.rows.name;
                $$('#loc').find('.item-title').text(name);

            }
        })
    }

    //解析定位错误信息
    function onError(data) {
        $$('#loc').find('.item-title').text('定位失败');
    }

    //给a标签添加点击事件
    $$('.location').find('a').once('click', choselocation);
    function choselocation() {
        var citycode = $$(this).find('.item-title').attr('citycode') || $$(this).attr('citycode');
        var cityname = $$(this).find('.item-title').html() || $$(this).html();
        if (!citycode) {
            $$('.location').find('a').once('click', choselocation);
            return;
        }
        localStorage.setItem('cityname', cityname);
        localStorage.setItem('citycode', citycode);
        mainView.router.back();
        myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.cinema-infinite-scroll'));
        $$("#locat").html(cityname);
        $$(".cinema").html('');
        var param = {
            lastIndex: $$(".cinema li").length,
            citycode: localStorage.citycode,
            lat: latitude,
            long: longitude
        };
        loading = true;
        getCinemaInfomation(cinemainfourl, param);
    };
});

myApp.onPageReinit('cinemadetail', function (page) {
    title('影院详情');
    var opt = {
        title: $$(page.container).find('.cinemaname').text(), // 分享标题
        desc: $$(page.container).find('.comment').text(),//分享描述
        link: window.location.host + sharecinemadetail + window.location.href.substring(window.location.href.lastIndexOf('?')), // 分享链接
        imgUrl: $$(page.container).find('.picture img').data('src'), // 分享图标
        success: function () {
        },
        cancel: function () {
        }
    }
    wx.onMenuShareAppMessage(opt);
    wx.onMenuShareTimeline(opt);
    wx.onMenuShareQQ(opt);
    wx.onMenuShareQZone(opt);
    wx.showOptionMenu();
});

myApp.onPageInit('cinemadetail', function (page) {
    title('影院详情');

    /**
     * 微信预约
     *  add by yan
     */
    var cinemaCode = page.query.cinema_code;
    var items = [];
    var list = myApp.virtualList($$('[data-page="cinemadetail"] .virtual-list'), {
        items: items,
        template: '<li>' +
        '<a href="cinemaroomtype?roomtype_id={{this.roomtype_id}}" class="item-link item-content">' +
        '<div class="item-inner" style="padding-right: 40%">' +
        '<div>' +
        '<div class="item-title-row" style="background-image: none">' +
        '<div class="item-title">{{this.roomtype_name}}</div>' +
        '</div>' +
        '<div class="item-subtitle">{{#if this.roomtype_description}}{{this.roomtype_description}}{{else}}-{{/if}}</div>' +
        '</div>' +
        '<div style="color: orange;font-size: 16px;position: absolute;right: 20%;top: 22px">{{formatPrice this.roomtype_price}}元/小时</div>' +
        '<object><a href="cinemaroomtype?roomtype_id={{this.roomtype_id}}" class="button button-fill color-orange" style="position: absolute;right: 3%;top: 20px">预约</a></object>' +
        '</div>' +
        '</a>' +
        '</li>',
        height: 63
    });

    if (cinemaCode) {
        $$.post('getcinemaroomtypes', {cinemacode: cinemaCode}, function (data) {
            data = JSON.parse(data);
            if (data.errorMessage) {
                $$('[data-page="cinemadetail"] .virtual-list').remove();
            } else if (data.rows.roomtype_list.length){
                list.appendItems(data.rows.roomtype_list);
            } else {
                $$('[data-page="cinemadetail"] .virtual-list').remove();
            }
            $$('[data-page="cinemadetail"] .infinite-scroll-preloader').remove();
        });
    }

    $$(page.container).find('.comment').on('click', function (e) {
        if ($$(this).css('-webkit-line-clamp') != 'none') {
            $$(this).data('line', $$(this).css('-webkit-line-clamp'));
            $$(this).css('-webkit-line-clamp', null);
        } else {
            $$(this).css('-webkit-line-clamp', $$(this).data('line'));
        }

    });

    $$(page.container).find('.collection').on('click', function (e) {
        var xin = $$(this);
        xin.attr("disabled", true);
        $$.ajax({
            url: updatecinemacollectionurl,
            method: 'POST',
            dataType: 'json',
            data: {
                cinema_code: $$(page.container).find('.cinemadetail').data('cinemacode'),
                open_id: open_id
            },
            success: function (data, status, xhr) {
                xin.removeAttr("disabled");
                if (data.status == 'error') {
                    myApp.alert(data.message);
                    return;
                } else {
                    if (data.message == '取消收藏成功') {
                        xin.removeClass('icon-xin4');
                        xin.addClass('icon-xin3');
                        var options = {},
                            toast = myApp.toast(data.message, '', options);
                        toast.show(true);

                    } else if (data.message == '收藏成功') {
                        xin.removeClass('icon-xin3');
                        xin.addClass('icon-xin4');
                        var options = {},
                            toast = myApp.toast(data.message, '', options);
                        toast.show(true);
                    }
                }
            },
            error: function (xhr, status) {
                xin.removeAttr("disabled");
            }
        });
    })


    $$('#map').on('click', function (e) {
        wx.openLocation({
            latitude: parseFloat($$(this).attr('lat')),
            longitude: parseFloat($$(this).attr('long')),
            name: $$(this).attr('name'),
            address: '地址：' + $$(this).attr('address') + '[右侧点击为您找到线路→_→]',
            scale: 14
        })
    })
});

myApp.onPageReinit('moviedetail', function (page) {
    title('影片详情');
    // mainView.router.refreshPage()
    mainView.router.load({url:'moviedetail',ignoreCache:true})
    var opt = {
        title: $$(page.container).find('.moviename').text(), // 分享标题
        desc: $$(page.container).find('p.detail').text(),
        link: window.location.host + sharemoviedetail + window.location.href.substring(window.location.href.lastIndexOf('?')), // 分享链接
        imgUrl: $$(page.container).find('.picture img').data('src'), // 分享图标
        success: function () {
        },
        cancel: function () {
        }
    };
    wx.onMenuShareAppMessage();
    wx.onMenuShareAppMessage(opt);
    wx.onMenuShareTimeline(opt);
    wx.onMenuShareQQ(opt);
    wx.onMenuShareQZone(opt);
    wx.showOptionMenu();
});

myApp.onPageInit('moviedetail', function (page) {
    title('影片详情');
    $$(page.container).find('.collect').on('click', function (e) {
        var xin = $$(this);
        xin.attr("disabled", true);
        $$.ajax({
            url: updatemoviecollectionurl,
            method: 'POST',
            dataType: 'json',
            data: {
                mid: $$(page.container).find('.moviedetail').data('mid'),
                open_id: open_id
            },
            success: function (data, status, xhr) {
                xin.removeAttr("disabled");
                if (data.status == 'error') {
                    myApp.alert(data.message);
                    return;
                } else {
                    if (data.message == '取消收藏成功') {
                        xin.removeClass('icon-xin4');
                        xin.addClass('icon-xin3');
                        var options = {},
                            toast = myApp.toast(data.message, '', options);
                        toast.show(true);
                    } else if (data.message == '收藏成功') {
                        xin.removeClass('icon-xin3');
                        xin.addClass('icon-xin4');
                        var options = {},
                            toast = myApp.toast(data.message, '', options);
                        toast.show(true);
                    }
                }
            },
            error: function (xhr, status) {
                xin.removeAttr("disabled");
            }
        });
    })

    $$(page.container).find('.detail').on('click', function (e) {
        if ($$(this).css('-webkit-line-clamp') != 'none') {
            $$(this).data('line', $$(this).css('-webkit-line-clamp'));
            $$(this).css('-webkit-line-clamp', null);
        } else {
            $$(this).css('-webkit-line-clamp', $$(this).data('line'));
        }
    });

    $$(page.container).find('.agree').on('click', function (e) {
        var xin1 = $$(this).find('.agreeimg');
        var that=this;
        xin1.attr("disabled", true);
        $$.ajax({
            url: '/postCommentAgree',
            method: 'POST',
            dataType: 'json',
            data: {
                agree: 0,
                open_id: open_id,
                id: $$(this).find('.agreeimg').data('id')
            },
            success: function (data, status, xhr) {
                // debugger
                xin1.removeAttr("disabled");
                if (!data.isSuccess) {
                    myApp.alert('点赞失败');
                    return;
                } else {
                    xin1.toggleClass("agree-like")
                    xin1.toggleClass("agree-common")
                    var value = parseInt($$(that).find('#like').text());
                    var flag = xin1.hasClass('agree-like');
                    if (flag) {
                        $$(that).find('#like').text(value + 1)
                    } else {
                        $$(that).find('#like').text(value - 1)
                    }
                }
            },
            error: function (xhr, status) {
                xin1.removeAttr("disabled");
                xin1.toggleClass("agree-like")
                xin1.toggleClass("agree-common")
            }
        });
    });

});

myApp.onPageInit('member', function (page) {
    title('会员中心');
    var navbarTemplate = '<div class="navbar">'
        + '<div class="navbar-inner">'
        + '<div class="left sliding">'
        + '<a href="#" class="link close-popup photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'
        + '<i class="icon icon-back {{iconsColorClass}}"></i>'
        + '{{#if backLinkText}}<span>{{backLinkText}}</span>{{/if}}'
        + '</a>'
        + '</div>'
        + '<div class="right"></div>'
        + '</div>'
        + '</div>'
    var myPhotoBrowser = myApp.photoBrowser({
        photos: [
            $$('#head').attr('src')
        ],
        backLinkText: '关闭图像',
        toolbar: false,
        navbarTemplate: navbarTemplate
    });
    $$('#head').on('click', function () {
        myPhotoBrowser.open();
    })
});

myApp.onPageReinit('member', function (page) {
    title('会员中心');
});

myApp.onPageInit('collectioncinema', function (page) {
    title('收藏影院');
    var map, geolocation;
//加载地图，调用浏览器定位服务
    map = new AMap.Map('iCenter');
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,        //超过10秒后停止定位，默认：无穷大
            maximumAge: 5000
        });
        map.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        geolocation.getCurrentPosition();
    });
//解析定位结果
    function onComplete(data) {
        latitude = data.position.getLat(); // 纬度，浮点数，范围为90 ~ -90
        longitude = data.position.getLng(); // 经度，浮点数，范围为180 ~ -180。
        var param = {
            lastIndex: $$(".cinema li").length,
            lat: latitude,
            long: longitude,
            open_id: open_id
        };
        getCinemaInfomation(collectioncinemainfourl, param);
    }

//解析定位错误信息
    function onError(data) {
        myApp.alert('获取地理信息失败');
        var param = {
            lastIndex: $$(".cinema li").length,
            lat: latitude,
            long: longitude,
            open_id: open_id
        };
        getCinemaInfomation(collectioncinemainfourl, param);
    };

    mySearchbar = myApp.searchbar('.collectioncinemasearchbar', {
        customSearch: true,
        onSearch: function () {
            if (cinemaxhr) {
                cinemaxhr.abort();
            }
            var param = {
                lastIndex: 0,
                lat: latitude,
                long: longitude,
                open_id: open_id,
                cinema_name: mySearchbar.query
            };
            myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.cinema-infinite-scroll'));
            $$(mainView.activePage.container).find('.cinema').html('');
            getCinemaInfomation(collectioncinemainfourl, param);
        }
    });

    $$('.cinema-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        $$('.cinema-infinite-scroll-preloader div').text('正在加载，请稍后...');
        // 设置flag
        loading = true;
        var param;

        param = {
            lastIndex: $$(".cinema li").length,
            //citycode: localStorage.citycode,
            cinema_name: mySearchbar.query,
            lat: latitude,
            long: longitude,
            open_id: open_id
        };

        getCinemaInfomation(collectioncinemainfourl, param);

    });

});

myApp.onPageReinit('collectioncinema', function (page) {
    title('收藏影院');
    wx.hideOptionMenu();
});

myApp.onPageInit('footprintcinema', function (page) {
    title('影院足迹');
    tempcreate_time = '';
    var map, geolocation;
//加载地图，调用浏览器定位服务
    map = new AMap.Map('iCenter');
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,        //超过10秒后停止定位，默认：无穷大
            maximumAge: 5000
        });
        map.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        geolocation.getCurrentPosition();
    });
//解析定位结果
    function onComplete(data) {
        latitude = data.position.getLat(); // 纬度，浮点数，范围为90 ~ -90
        longitude = data.position.getLng(); // 经度，浮点数，范围为180 ~ -180。
        var param = {
            lastIndex: $$(".cinema li").length,
            lat: latitude,
            long: longitude,
            open_id: open_id
        };
        getCinemaInfomation(footprintcinemainfourl, param);
    }

//解析定位错误信息
    function onError(data) {
        myApp.alert('获取地理信息失败');
        var param = {
            lastIndex: $$(".cinema li").length,
            lat: latitude,
            long: longitude,
            open_id: open_id
        };
        getCinemaInfomation(footprintcinemainfourl, param);
    };

    $$('.cinema-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        var param;
        param = {
            lastIndex: $$(".cinema li").length,
            //citycode: localStorage.citycode,
            lat: latitude,
            long: longitude,
            open_id: open_id
        };
        getCinemaInfomation(footprintcinemainfourl, param);

    });

});

myApp.onPageReinit('footprintcinema', function (page) {
    title('影院足迹');
    wx.hideOptionMenu();
});

myApp.onPageInit('footprintmovie', function (page) {
    title('影片足迹');
    tempcreate_time = '';
    var param = {
        lastIndex: $$(".movie li").length,
        open_id: open_id
    };
    getMovieINFO(footprintmovieinfourl, param);

    $$('.movie-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        var param;
        param = {
            lastIndex: $$(".movie li").length,
            open_id: open_id
        };
        getMovieINFO(footprintmovieinfourl, param);

    });

});

myApp.onPageReinit('footprintmovie', function (page) {
    title('影片足迹');
    wx.hideOptionMenu();
});

myApp.onPageInit('collectionmovie', function (page) {
    title('收藏影片');
    var mySearchbar = myApp.searchbar('.collectionmoviesearchbar', {
        customSearch: true,
        onSearch: function () {
            if (moviexhr) {
                moviexhr.abort();
            }
            var param = {
                lastIndex: 0,
                movie_name: mySearchbar.query,
                open_id: open_id
            };
            myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
            $$(mainView.activePage.container).find('.movie').html('');
            $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('正在加载，请稍后...');
            getMovieINFO(collectionmovieinfourl, param);
        }
    });

    var param = {
        lastIndex: $$(".movie li").length,
        open_id: open_id
    };
    getMovieINFO(collectionmovieinfourl, param);

    $$('.movie-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('正在加载，请稍后...');
        // 设置flag
        loading = true;
        var param;
        param = {
            lastIndex: $$(".movie li").length,
            cinema_name: mySearchbar.query,
            open_id: open_id
        }
        getMovieINFO(collectionmovieinfourl, param);

    });
});

myApp.onPageReinit('collectionmovie', function (page) {
    title('收藏影片');
    wx.hideOptionMenu();
});

myApp.onPageInit('userchange', function (page) {
    title('登录其他账户');
    var flag = true;
    $$('#identifyingcodec').attr("src", 'identifyingcode?open_id=' + open_id + '&random=' + Math.random());
    $$('#identifyingcodec').on('click', function () {
        if (flag) {
            $$(this).attr("src", 'identifyingcode?open_id=' + open_id + '&random=' + Math.random());
            flag = false;
            setTimeout(function () {
                flag = true;
            }, 500)
        } else {

        }
    });
//校验手机号是否合法
    function isPhoneNum() {
        var phonenum = $$("#phonenumberc").val();
        var myreg = /^1[34578]\d{9}$/;
        if (!myreg.test(phonenum)) {
            myApp.alert('请输入有效的手机号码！');
            return false;
        } else {
            return true;
        }
    }

    var Count = {
        node: null,
        count: 60,
        start: function () {
            //console.log(this.count);
            if (this.count > 0) {
                this.node.text(this.count-- + "秒后重试");
                var _this = this;
                setTimeout(function () {
                    _this.start();
                }, 1000);
            } else {
                this.node.removeAttr("disabled");
                this.node.text("获取验证码");
                this.count = 60;
            }
        },
        //初始化
        init: function (node) {
            this.node = node;
            this.node.attr("disabled", true);
            this.start();
        },
        stop: function (node) {
            this.node = node;
            this.node.text("获取验证码");
            this.node.removeAttr("disabled");
        }
    };

    $$('#vcodec').on('click', function (e) {
        // mainView.router.back();
        var btn = $$(this);
        if (!isPhoneNum()) {
            return;
        }
        if ($$('#identifyingc').val().trim() == '' || $$('#identifyingc').val().length != 4) {
            myApp.alert('请输入正确的验证码');
            btn.removeAttr("disabled");
        } else {
            btn.attr("disabled", true);
            // alert(open_id);
            $$.ajax({
                url: '/loginsms',
                method: 'POST',
                dataType: 'json',
                data: {
                    identifyingcode: $$('#identifyingc').val(),
                    phone: $$('#phonenumberc').val(),
                    open_id: open_id
                },
                success: function (data, status, xhr) {
                    if (data.status == 'error') {
                        myApp.alert(data.message);
                        $$("#identifyingcodec").attr("src", 'identifyingcode?' + "open_id=" + open_id + '&random=' + Math.random());
                        btn.removeAttr("disabled");
                        return;
                    } else {
                        Count.init(btn);
                    }
                },
                error: function (xhr, status) {
                    btn.removeAttr("disabled");
                }
            });
        }
    })

    $$('#submit2').on('click', function () {
        var sumbit = $$(this);
        if (!isPhoneNum()) {
            return
        }
        if ($$('#identifyingc').val().trim() == '' || $$('#identifyingc').val().length != 4) {
            myApp.alert('请输入正确的验证码');
            btn.removeAttr("disabled");
        } else {
            $$.ajax({
                // 向后台传递手机号     $$('#identifying').val()
                url: '/changeuser',
                method: 'POST',
                dataType: 'json',
                data: {
                    smscode: $$('#smscodec').val(),
                    phone: $$('#phonenumberc').val(),
                    open_id: open_id
                },
                success: function (data, status, xhr) {
                    sumbit.removeAttr("disabled");
                    if (data.status == 'error') {
                        myApp.alert(data.message);
                        $$("#identifyingcodec").attr("src", 'identifyingcode?&random=' + Math.random());
                        return;
                    } else {
                        if (data.status == 'success') {
                            $$('.page-on-left').remove();
                            mainView.router.back({reloadPrevious: true, ignoreCache: true});
                        } else if (data.status == 'fail') {
                            myApp.alert(data.message, function () {
                                $$('#smscodec').val('');
                                $$('#identifyingc').val('');
                                $$("#identifyingcodec").attr("src", 'identifyingcode?&random=' + Math.random());
                            });
                        }
                    }

                },
                error: function (xhr, status) {
                    sumbit.removeAttr("disabled");
                }
            });
        }
    })
});

myApp.onPageReinit('userchange', function (page) {
    title('登录其他账户');
});

myApp.onPageInit('login', function (page) {
    title('会员登录');
    var flag = true;
    $$('#identifyingcode').attr("src", 'identifyingcode?&random=' + Math.random());
    $$('#identifyingcode').on('click', function () {
        if (flag) {
            $$(this).attr("src", 'identifyingcode?&random=' + Math.random());
            flag = false;
            setTimeout(function () {
                flag = true;
            }, 500)
        }
    });
//校验手机号是否合法
    function isPhoneNum() {
        var phonenum = $$("#phonenumber").val();
        var myreg = /^1[34578]\d{9}$/;
        if (!myreg.test(phonenum)) {
            myApp.alert('请输入有效的手机号码！');
            return false;
        } else {
            return true;
        }
    }

    var Count = {
        node: null,
        count: 60,
        start: function () {
            //console.log(this.count);
            if (this.count > 0) {
                this.node.text(this.count-- + "秒后重试");
                var _this = this;
                setTimeout(function () {
                    _this.start();
                }, 1000);
            } else {
                this.node.removeAttr("disabled");
                this.node.text("获取验证码");
                this.count = 60;
            }
        },
        //初始化
        init: function (node) {
            this.node = node;
            this.node.attr("disabled", true);
            this.start();
        }
    };

    $$('#vcode').on('click', function (e) {
        var btn = $$(this);
        if (!isPhoneNum()) {
            return
        }
        if ($$('#identifying').val().trim() == '' || $$('#identifying').val().length != 4) {
            myApp.alert('请输入正确的验证码');
            btn.removeAttr("disabled");
        } else {
            btn.attr("disabled", true);
            $$.ajax({
                url: '/loginsms',
                method: 'POST',
                dataType: 'json',
                data: {
                    identifyingcode: $$('#identifying').val(),
                    phone: $$('#phonenumber').val(),
                    open_id: open_id
                },
                success: function (data, status, xhr) {
                    if (data.status == 'error') {
                        myApp.alert(data.message);
                        $$("#identifyingcode").attr("src", 'identifyingcode?' + '&random=' + Math.random());
                        btn.removeAttr("disabled");
                        return;
                    } else {
                        Count.init(btn);
                    }
                },
                error: function (xhr, status) {
                    btn.removeAttr("disabled");
                }
            });

        }


    })

    $$('#submit').on('click', function () {
        var sumbit = $$(this);
        if (!isPhoneNum()) {
            return
        }
        if ($$('#identifying').val().trim() == '' || $$('#identifying').val().length != 4) {
            myApp.alert('请输入正确的验证码');
        } else {
            sumbit.attr("disabled", true);
            $$.ajax({
                // 向后台传递手机号     $$('#identifying').val()
                url: '/loginConfirm',
                method: 'POST',
                dataType: 'json',
                data: {
                    smscode: $$('#smscode').val(),
                    phone: $$('#phonenumber').val(),
                    open_id: open_id
                },
                success: function (data, status, xhr) {
                    sumbit.removeAttr("disabled");
                    if (data.status == 'error') {
                        myApp.alert(data.message);
                        return;
                    } else {
                        if (data.status == 'success') {
                            mainView.router.reloadPage('member?open_id=' + open_id + '&random=' + Math.random());
                        } else if (data.status == 'fail') {
                            myApp.alert(data.message, function () {
                                $$('#smscode').val('');
                                $$('#identifying').val('');
                                $$("#identifyingcode").attr("src", 'identifyingcode?' + '&random=' + Math.random());
                            });
                        }
                    }
                },
                error: function (xhr, status) {
                    sumbit.removeAttr("disabled");
                },
                complete: function (xhr, status) {
                }
            });

        }


    })

});

myApp.onPageReinit('login', function (page) {
    title('会员登录');
});

myApp.onPageInit('changephone', function (page) {
    title('修改手机号');
    $$('#pppp').attr("src", 'identifyingcode?open_id=' + open_id + '&random=' + Math.random());
    function isPhoneNum() {
        var oldphonenum = $$("#oldphonenumber").val();
        var newphonenum = $$("#newphonenumber").val();
        var myreg = /^1[34578]\d{9}$/;
        if (!myreg.test(oldphonenum)) {
            myApp.alert('请输入有效的原手机号码！');
            return false;
        } else if (!myreg.test(newphonenum)) {
            myApp.alert('请输入有效的新手机号码！');
            return false;
        } else if (oldphonenum == newphonenum) {
            myApp.alert('两手机号一致，无需更改');
            return false;
        } else {
            return true;
        }
    };
    var Count = {
        node: null,
        count: 60,
        start: function () {
            //console.log(this.count);
            if (this.count > 0) {
                this.node.text(this.count-- + "秒后重试");
                var _this = this;
                setTimeout(function () {
                    _this.start();
                }, 1000);
            } else {
                this.node.removeAttr("disabled");
                this.node.text("获取验证码");
                this.count = 60;
            }
        },
        //初始化
        init: function (node) {
            this.node = node;
            this.node.attr("disabled", true);
            this.start();
        }
    };

    $$('#vcode2').on('click', function () {
        var btn = $$(this);
        if (!isPhoneNum()) {
            return
        }
        if ($$('#identifying2').val().trim() == '' || $$('#identifying2').val().length != 4) {
            myApp.alert('请输入正确的验证码');
            btn.removeAttr("disabled");
        } else {
            btn.attr("disabled", true);
            $$.ajax({
                url: '/loginsms',
                method: 'POST',
                dataType: 'json',
                data: {
                    identifyingcode: $$('#identifying2').val(),
                    phone: $$('#newphonenumber').val(),
                    open_id: open_id
                    // {data:[a,b,c]}
                },
                success: function (data, status, xhr) {
                    if (data.status == 'error') {
                        myApp.alert(data.message);
                        $$("#pppp").attr("src", 'identifyingcode?' + "open_id=" + open_id + '&random=' + Math.random());
                        btn.removeAttr("disabled");
                        //mainView.router.reloadPage('member?open_id='+open_id + '&random=' + Math.random());
                        // if (data.message=='查无手机'){
                        //     //跳转注册页面
                        // }else if(data.message=='手机更换失败'){
                        //     //跳转注册页面
                        // }
                        return;
                    } else {
                        if (data.status == 'success') {
                            //  mainView.router.back();
                            Count.init(btn);
                        } else {
                            myApp.alert('短信验证码发送失败');
                            btn.removeAttr("disabled");
                        }

                    }
                },
                error: function (xhr, status) {
                    btn.removeAttr("disabled");
                }
            });
        }

    });

    var flag = true;
    $$('#pppp').on('click', function () {
        if (flag) {
            $$(this).attr("src", 'identifyingcode?open_id=' + open_id + '&random=' + Math.random());
            flag = false;
            setTimeout(function () {
                flag = true;
            }, 500)
        }
    });

    $$('#submit').on('click', function () {
        var sumbit = $$(this);
        if (!isPhoneNum()) {
            return
        }

        if ($$('#smscode2').val().trim() == '' || $$('#smscode2').val().length != 4) {
            myApp.alert('请输入正确的验证码');
            ;
        } else {
            sumbit.attr("disabled", true);
            // alert($$('#smscode2').val());
            $$.ajax({
                url: '/getchangemobile',
                method: 'POST',
                dataType: 'json',
                data: {
                    smscode: $$('#smscode2').val(),
                    oldphonenumber: $$('#oldphonenumber').val(),
                    newphonenumber: $$('#newphonenumber').val(),
                    ident: $$('#ident').val(),
                    open_id: open_id
                },
                success: function (data, status, xhr) {
                    sumbit.removeAttr("disabled");
                    if (data.status == 'error') {
                        myApp.alert(data.message);
                        $$("#pppp").attr("src", 'identifyingcode?' + "open_id=" + open_id + '&random=' + Math.random());
                        return;
                    } else {
                        if (data.status == 'success') {
                            myApp.alert('手机更换成功');
                            mainView.router.back();
                        }
                    }
                },
                error: function (xhr, status) {
                    sumbit.removeAttr("disabled");
                }
            });

        }


    })


});

myApp.onPageReinit('changephone', function (page) {
    title('修改手机号');
});

myApp.onPageInit('membercard', function (page) {
    title('会员卡');
    var tel = $$('.membercard-bar-no').text();
    var canvas = qrcanvas({
        data: tel,
        cellSize: 10
    });
    var navbarTemplate =
        +'<div class="navbar-inner">'
        + '<div class="left sliding">'
        + '<a href="#" class="link close-popup photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'
        + '<i class="icon icon-back {{iconsColorClass}}"></i>'
        + '{{#if backLinkText}}<span>{{backLinkText}}</span>{{/if}}'
        + '</a>'
        + '</div>'
        + '<div class="right"></div>'
        + '</div>'
        + '</div>';
    var photoTemplate = '<div class="page-content login-screen-content" style="width: 100%;background-color: #0a6ebd"><div class="login-screen-title">尊享会员特权</div>'
        + '<div style="text-align: center;">'
        + '<div class="container card"  style="margin:auto;padding:20px 10px;width: 85%;background-color: white"></div></div>'
        + '</div>';


    var myPhotoBrowser = myApp.photoBrowser({
        photos: [' '],
        backLinkText: '关闭二维码',
        toolbar: false,
        navbarTemplate: navbarTemplate,
        photoTemplate: photoTemplate,
        type: 'page',
    });


    $$('#qrlogo').on('click', function () {
        myPhotoBrowser.open();
        title('会员二维码')
        myPhotoBrowser.container.find('.container').append(canvas);
        myPhotoBrowser.container.find('.container').append('<div><h4>' + tel + '</h4></div>');
    });
});

myApp.onPageReinit('membercard', function (page) {
    title('会员卡')
})
//影片搜索 start
myApp.onPageReinit('moviesearch', function (page) {
    title('观影频道');
    wx.hideOptionMenu();
});

myApp.onPageInit('moviesearch', function (page) {
    title('观影频道');
    var map, geolocation;
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('iCenter');
    map.plugin('AMap.Geolocation', function () {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        });
        map.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        geolocation.getCurrentPosition();
    });
    //解析定位结果
    function onComplete(data) {
        latitude = data.position.getLat(); // 纬度，浮点数，范围为90 ~ -90
        longitude = data.position.getLng(); // 经度，浮点数，范围为180 ~ -180。

        // myApp.alert(latitude); myApp.alert(longitude);
        var str = 'geo=' + latitude + '-' + longitude
        document.cookie = str;
        // myApp.alert(str);
    }

    //解析定位错误信息
    function onError(data) {
        // $$('#loc').find('.item-title').text('定位失败');
        myApp.alert("定位失败");
        var str = 'geo=' + latitude + '-' + longitude
        document.cookie = str;
    }
})
//影片搜索 end
var cinemaxhr;
function getCinemaInfomation(url, param) {
    $$(mainView.activePage.container).find('.cinema-infinite-scroll-preloader div').text('正在加载，请稍后...');
    cinemaxhr = $$.post(url,
        param,
        function (data) {
            if (data.length == 0) {
                return;
            }
            var data = JSON.parse(data);
            if (data.status = 'success') {
                setCinemaForm(data.data);
                cinemaxhr = null;
            } else {
                myApp.alert("出现故障");
                return;
            }
            if (data.data.length < 10) {
                myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.cinema-infinite-scroll'));
                $$(mainView.activePage.container).find('.cinema-infinite-scroll-preloader div').text('加载完毕，没有更多数据');
            } else if (data.data.length == 10 && $$(".cinema li").length == 10) {
                myApp.attachInfiniteScroll($$(mainView.activePage.container).find('.cinema').parents('.page-content'));
                $$(mainView.activePage.container).find('.cinema-infinite-scroll-preloader div').text('上拉加载更多');
            } else {
                $$(mainView.activePage.container).find('.cinema-infinite-scroll-preloader div').text('上拉加载更多');
            }
        });
}


var moviexhr;

function getMovieINFO(url, param) {
    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('正在加载请稍后...');
    moviexhr = $$.post(url,
        param,
        function (data) {
            var data = JSON.parse(data);
            if (data.status = 'success') {
                setMovieForm(data.data);
                moviexhr = null;
            } else {
                return;
            }
            if (data.data.length < 10) {
                myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
                $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('加载完毕，没有更多数据');
            } else if (data.data.length == 10 && $$(mainView.activePage.container).find(".movie li").length == 10) {
                myApp.attachInfiniteScroll($$(mainView.activePage.container).find('.movie').parents('.page-content'));
                $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('上拉加载更多');
            } else {
                $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('上拉加载更多');
            }
        });
}

myApp.onPageReinit('movielib', function (page) {
    title('影院片库');
    wx.hideOptionMenu();
});


var loading;
myApp.onPageInit('movielib', function (page) {
    title('影院片库');
    findMovieLibByParam();
    updataFilterByMovie();

    var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
    var _paramMovieType = [];
    for (var i = 0; i < chooseMovieTypeLength; i++) {
        _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
    }

    getMovieInfomation({
        'param_pageSize': '',
        'cinemaCode': $$(".movie").data('cinemaCode'),
        'sort': 0,
        'movieType': '',
        'movieCountry': '',
        'movieYear': 0,
        'movieName': moviemySearchbar.query
    });


    // 加载flag
    loading = false;

    $$('.movie-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;

        // 设置flag
        loading = true;
        var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
        var _paramMovieType = [];
        for (var i = 0; i < chooseMovieTypeLength; i++) {
            _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
        }
        getMovieInfomation({
            'param_pageSize': $$(mainView.activePage.container).find('.movie').find('li').length,
            'cinemaCode': $$(".movie").data('cinemaCode'),
            'sort': $$('.content-block').eq(0).find('.buttonactive').data('sort'),
            'movieType': JSON.stringify(_paramMovieType),
            'movieCountry': $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
            'movieYear': $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
            'movieName': moviemySearchbar.query
        });

    });

    $$('.open-popover').on('click', function () {
        var clickedLink = this;
        var popoverHTML = '<div class="popover" style="width: 45%;height: 10%;text-align: center;">' +
            '<div class="content-block" style="margin-top:0px;">' +
            '<p style="margin: auto;margin-top: 16%">' + $$(this).text().replace(/\//g, ' ') + '</p>' +
            '</div>' +
            '</div>';
        myApp.popover(popoverHTML, clickedLink);
    });


});


$$('.accordion-item').on('opened', function () {
    if ($$(this).find('i').text() == 'chevron_down') {
        $$(this).find('.item-title').html('');
        var html = '';
        html += '<i class="f7-icons" style="color: #FFFFFF;font-size: small">chevron_up</i>';
        $$(this).find('.item-title').append(html);
    }
});

$$('.accordion-item').on('closed', function (e) {
    if ($$(this).find('i').text() == 'chevron_up') {
        $$(this).find('.item-title').html('');
        var html = '';
        html += '<i class="f7-icons" style="color: #FFFFFF;font-size: small">chevron_down</i>';
        $$(this).find('.item-title').append(html);
    }
});

/**
 * 右侧栏打开事件
 */
$$('.panel-right').on('open', function () {
    myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
});

/**
 * 右侧栏关闭事件  --  发起查询请求
 */
$$('.panel-right').on('closed', function (e) {
    myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
    $$('.movie').html('');
    var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
    var _paramMovieType = [];
    for (var i = 0; i < chooseMovieTypeLength; i++) {
        _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
    }

    var viewname = myApp.getCurrentView().activePage.name;
    if (viewname == 'moviesearchlib') {
        title("影片一览");
    }

    var str = myApp.getCurrentView().activePage.name;

    if (str == 'moviesearchlib') {
        // myApp.alert(str);
        $$(mainView.activePage.container).find('.moviesearch').html('');

        // var list = $$('.content-block').find('.buttonactive').text();
        // var titleName='';
        // list.forEach(function(e){
        //     if (e!='新上榜'&&e!='全部')
        //     {
        //         titleName+=e+' ';
        //     }
        // });
        // title(titleName);

        getMovieSearchLibInfo(
            {
                'param_pageSize': $$(mainView.activePage.container).find('.movie').find('li').length,
                // 'cinemaCode': $$(".movie").data('cinemaCode'),
                'sort': $$('.content-block').eq(0).find('.buttonactive').data('sort'),
                'movieType': JSON.stringify(_paramMovieType),
                'movieCountry': $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
                'movieYear': $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
                'movieName': toolmoviemySearchbar.query
            }
        )
    } else {
        //   myApp.alert(123123);
        getMovieInfomation({
            'param_pageSize': $$(mainView.activePage.container).find('.movie').find('li').length,
            'cinemaCode': $$(".movie").data('cinemaCode'),
            'sort': $$('.content-block').eq(0).find('.buttonactive').data('sort'),
            'movieType': JSON.stringify(_paramMovieType),
            'movieCountry': $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
            'movieYear': $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
            'movieName': moviemySearchbar.query
        });
    }


});

function getMovieInfomation(param) {
    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('正在加载，请稍后...');
    $$.post('/movielib',
        param,
        function (data) {
            var data = JSON.parse(data);
            if (data.status === 'success') {
                setMovieForm(data.data);
                if (data.data.length < 10) {
                    myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
                    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('已无更多影片');
                } else if (data.data.length == 10 && $$(mainView.activePage.container).find('.movie').find('li').length == 10) {
                    myApp.attachInfiniteScroll($$(mainView.activePage.container).find('.movie').parents('.page-content'));
                    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('上拉加载更多');
                } else {
                    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('上拉加载更多');
                }
            }

        });
}
myApp.onPageReinit('moviesearchlib', function (page) {
    title('影片一览');
    wx.hideOptionMenu();
});
myApp.onPageInit('moviesearchlib', function (page) {
    title('影片一览');
    toolupdataFilterByMovie(page);

    $$('.open-popover').on('click', function () {
        var clickedLink = this;
        var popoverHTML = '<div class="popover" style="width: 45%;height: 10%;text-align: center;">' +
            '<div class="content-block" style="margin-top:0px;">' +
            '<p style="margin: auto;margin-top: 16%">' + $$(this).text().replace(/\//g, ' ') + '</p>' +
            '</div>' +
            '</div>';
        myApp.popover(popoverHTML, clickedLink);
    });

    toolmoviemySearchbar = myApp.searchbar('.cinemamoviesearchbar-film', {
        customSearch: true,
        onSearch: function () {
            myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
            $$(mainView.activePage.container).find('.moviesearch').html('');
            var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
            var _paramMovieType = [];
            for (var i = 0; i < chooseMovieTypeLength; i++) {
                _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
            }
            var param = {
                param_pageSize: $$(mainView.activePage.container).find('.moviesearch').find('li').length,
                sort: $$('.content-block').eq(0).find('.buttonactive').data('sort'),
                movieType: JSON.stringify(_paramMovieType),
                movieCountry: $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
                movieYear: $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
                movieName: toolmoviemySearchbar.query
            };
            title('影片一览');
            getMovieSearchLibInfo(param);

            $$('.open-popover').on('click', function () {
                var clickedLink = this;
                var popoverHTML = '<div class="popover" style="width: 45%;height: 10%;text-align: center;">' +
                    '<div class="content-block" style="margin-top:0px;">' +
                    '<p style="margin: auto;margin-top: 16%">' + $$(this).text().replace(/\//g, ' ') + '</p>' +
                    '</div>' +
                    '</div>';
                myApp.popover(popoverHTML, clickedLink);
            });
        }
    });


    myApp.attachInfiniteScroll($$(mainView.activePage.container).find('.moviesearch').parents('.page-content'));
    // 加载flag
    loading = false;

    $$('.movie-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
        var _paramMovieType = [];
        for (var i = 0; i < chooseMovieTypeLength; i++) {
            _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
        }
        getMovieSearchLibInfo({
            'param_pageSize': $$(mainView.activePage.container).find('.moviesearch').find('li').length,
            // 'cinemaCode': $$(".movie").data('cinemaCode'),
            'sort': $$('.content-block').eq(0).find('.buttonactive').data('sort'),
            'movieType': JSON.stringify(_paramMovieType),
            'movieCountry': $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
            'movieYear': $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
            'movieName': toolmoviemySearchbar.query
        });


    });


});


/**
 *  添加评论
 * @param param
 */
myApp.onPageInit('newcomment', function (page) {
    title('添加评论');

    var num = finalnum = tempnum = 1;
    var lis = $$('.star li')
    //num:传入点亮星星的个数
    //finalnum:最终点亮星星的个数
    //tempnum:一个中间值
    function fnShow(num) {
        finalnum = num || tempnum;//如果传入的num为0，则finalnum取tempnum的值
        for (var i = 0; i < lis.length; i++) {
            lis[i].className = i < finalnum ? "light" : "";//点亮星星就是加class为light的样式
        }
    }

    for (var i = 1; i <= lis.length; i++) {
        lis[i - 1].index = i;
        lis[i - 1].onmouseover = function () { //鼠标经过点亮星星。
            fnShow(this.index);//传入的值为正，就是finalnum
        }
        lis[i - 1].onmouseout = function () { //鼠标离开时星星变暗
            fnShow(0);//传入值为0，finalnum为tempnum,初始为0
        }
        lis[i - 1].onclick = function () { //鼠标点击,同时会调用onmouseout,改变tempnum值点亮星星
            tempnum = this.index;
            num = tempnum;
            fnShow(this.index);
            var j = 0;
        }
    }


    $$('#addcomment').on('click',
        function () {
            var text = $$('#text').val();
            var name, value;
            var str = location.href; //取得整个地址栏
            var numm = str.indexOf("?")
            // str = str.substr(numm + 1); //取得所有参数   stringvar.substr(start [, length ]
            var mid = str.match(/mid=(\S*)/)[1];
            $$.ajax({
                url: '/postaddcomment',
                method: 'post',
                data: {
                    mid: mid,
                    num: num,
                    text: text
                },
                success: function (data, status, xhr) {
                    data = JSON.parse(data)
                    var str = data.isSuccess ? '发布评论成功' : '服务器内部错误'
                    myApp.alert(str, '', function () {
                        $$('.page-on-left').remove();
                        mainView.router.back({reloadPrevious: true, ignoreCache: true});
                        // mainView.router.reloadPage('moviedetail');
                        // mainView.router.back({reloadPrevious: true, ignoreCache: true});
                    });
                },
                error: function (xhr, status) {
                    myApp.alert('服务器错误', '', function () {
                        mainView.router.reloadPage('moviedetail');
                    });
                },
                complete: function (xhr, status) {
                }
            })
        }
    );

})
myApp.onPageReinit('newcomment', function (page) {

})


/**
 *  添加评论回复
 * @param param
 */
myApp.onPageInit('replycomment', function (page) {
    title('评论回复');
    $$('#addcomment').on('click',
        function () {
            var text = $$('#text').val();
            var str = location.href; //取得整个地址栏
            var mid = str.match(/mid=(\w*)/)[1];
            var cid = str.match(/cid=(\w*)&/)[1];
            var name = str.match(/name=(\w*)&/)[1];
            if (text.trim() == '') {
                myApp.alert('输入内容不能为空！');
                return;
            }
            $$.ajax({
                url: '/postreplycomment',
                method: 'post',
                data: {
                    cid: cid,
                    mid: mid,
                    name: name,
                    text: '(回复：' + name + ') ' + text
                },
                success: function (data, status, xhr) {
                    data = JSON.parse(data)
                    var str = data.isSuccess ? '发布评论成功' : '服务器内部错误'
                    myApp.alert(str, '', function () {

                        $$('.page-on-left').remove();
                        mainView.router.back({reloadPrevious: true, ignoreCache: true});
                    });
                },
                error: function (xhr, status) {
                    myApp.alert('服务器错误', '', function () {
                        mainView.router.reloadPage('moviedetail');
                    });
                },
                complete: function (xhr, status) {
                }
            })
        }
    );

})
myApp.onPageReinit('replycomment', function (page) {

})

/**
 * 评论列表
 * @param param
 */
myApp.onPageInit('morecomment', function (page) {
    var str = location.href; //取得整个地址栏
    var numm = str.indexOf("?")
    str = str.substr(numm + 1); //取得所有参数   stringvar.substr(start [, length ]
    var a = str.match(/mname=(\S*)&/)[1];
    var mid = str.match(/mid=(\S*)/)[1];
    title(a + ' 的评论');
    var loading = false;

    $$(mainView.activePage.container).find('.comment-infinite-scroll-preloader div').text('加载完毕，没有更多数据');

    let commentxhr;
    $$('.comment-infinite-scroll').on('infinite', function () {
        // 如果正在加载，则退出
        if (loading) return;
        // 设置flag
        loading = true;
        let param;
        param = {
            lastIndex: $$(mainView.activePage.container).find(".comment li").length,
            mid: mid
        }
        commentxhr = $$.post('postCommentListByPage',
            param,
            function (data) {
                var data = JSON.parse(data);
                if (data.isSuccess) {

                    if (data.data && data.data.rows.length > 0 && data.data.rows[0].headimgurl) {
                        try {
                            var html = '';
                            $$.each(data.data.rows, function (i, v) {
                                console.log(v.headimgurl)
                                html += '<li>    <div class="item-content ">        <div class="item-title-row" style="width: 100%">            <div style="width: 70%">                <img src=';
                                html += v.headimgurl;
                                html += ' alt="" class="headimg"   style="    float: left;    width: 30px;    height: 30px;    border-radius: 50%;margin-top: 5px"/> <div class="inline-center" style="color:#7EC0EE;padding-top: 0px">'
                                html += v.nickname
                                html += '</span> </div><div class="date-comment">'
                                html += v.create_time
                                html += '</div><div class="star-'
                                html += v.score
                                html += '"></div>  </div>            <div class="agree" style="float: right;margin-right: 5px">  <span class="inline-center" id="like" style="float: right;vertical-align: middle; margin-left: 3px !important;">'
                                html += v.sums
                                html += '</span>'
                                html += '<div class="agreeimg agree-'
                                if (v.agreed) {
                                    html += 'like'
                                } else {
                                    html += 'common'
                                }
                                html += '" data-id="'
                                html += v.id
                                html += '" style="float: right;width: 20px;height: 20px;vertical-align: middle;margin-top: 12px"></div>'
                                html += ' </div>        </div>    </div>    <div class="item-content">        <div style="display: block">            <p class="detail comment-left" style="-webkit-line-clamp:7  ;">'
                                html += v.comment
                                html += '</p></div></div></li>'
                            })
                            $$(mainView.activePage.container).find('.comment').append(html);

                            $$(page.container).find('.agree').on('click', function (e) {
                                var xin1 = $$(this).find('.agreeimg');
                                var that=this;
                                xin1.attr("disabled", true);
                                $$.ajax({
                                    url: '/postCommentAgree',
                                    method: 'POST',
                                    dataType: 'json',
                                    data: {
                                        agree: 0,
                                        open_id: open_id,
                                        id: $$(this).find('.agreeimg').data('id')
                                    },
                                    success: function (data, status, xhr) {
                                        // debugger
                                        xin1.removeAttr("disabled");
                                        if (!data.isSuccess) {
                                            myApp.alert('点赞失败');
                                            return;
                                        } else {
                                            xin1.toggleClass("agree-like")
                                            xin1.toggleClass("agree-common")
                                            var value = parseInt($$(that).find('#like').text());
                                            var flag = xin1.hasClass('agree-like');
                                            if (flag) {
                                                $$(that).find('#like').text(value + 1)
                                            } else {
                                                $$(that).find('#like').text(value - 1)
                                            }
                                        }
                                    },
                                    error: function (xhr, status) {
                                        xin1.removeAttr("disabled");
                                        xin1.toggleClass("agree-like")
                                        xin1.toggleClass("agree-common")
                                    }
                                });
                            });
                        } catch (err) {
                            console.log('error')
                        }
                    }
                    loading = false;
                } else {
                    myApp.alert("出现故障");
                    return;
                }
                if (data.data.rows.length < 10) {
                    myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.comment-infinite-scroll'));
                    $$(mainView.activePage.container).find('.comment-infinite-scroll-preloader div').text('加载完毕，没有更多数据');
                } else if (data.data.rows.length == 10 && $$(".comment li").length == 10) {
                    myApp.attachInfiniteScroll($$(mainView.activePage.container).find('.cinema').parents('.page-content'));
                    $$(mainView.activePage.container).find('.comment-infinite-scroll-preloader div').text('上拉加载更多');
                } else {
                    $$(mainView.activePage.container).find('.comment-infinite-scroll-preloader div').text('上拉加载更多');
                }
            }
        );

    });

    //点击评论，弹出回复窗口
    $$(page.container).find('.item-content').on('click', function () {
        var name = $$(this).find('.inline-center').text();
        console.log(name)
    })
    $$(page.container).find('.agree').on('click', function (e) {
        var xin1 = $$(this).find('.agreeimg');
        var that=this;
        xin1.attr("disabled", true);
        $$.ajax({
            url: '/postCommentAgree',
            method: 'POST',
            dataType: 'json',
            data: {
                agree: 0,
                open_id: open_id,
                id: $$(this).find('.agreeimg').data('id')
            },
            success: function (data, status, xhr) {
                // debugger
                xin1.removeAttr("disabled");
                if (!data.isSuccess) {
                    myApp.alert('点赞失败');
                    return;
                } else {
                    xin1.toggleClass("agree-like")
                    xin1.toggleClass("agree-common")
                    var value = parseInt($$(that).find('#like').text());
                    var flag = xin1.hasClass('agree-like');
                    if (flag) {
                        $$(that).find('#like').text(value + 1)
                    } else {
                        $$(that).find('#like').text(value - 1)
                    }
                }
            },
            error: function (xhr, status) {
                xin1.removeAttr("disabled");
                xin1.toggleClass("agree-like")
                xin1.toggleClass("agree-common")
            }
        });
    });
    $$('#addcomment').on('click', function () {
            var text = $$('#text').val();
            var name, value;

            $$.ajax({
                url: '/postaddcomment',
                method: 'post',
                data: {
                    mid: mid,
                    num: num,
                    text: text
                },
                success: function (data, status, xhr) {
                    data = JSON.parse(data)
                    var str = data.isSuccess ? '发布评论成功' : '服务器内部错误'
                    myApp.alert(str, '', function () {
                        mainView.router.reloadPage('moviedetail');
                    });
                },
                error: function (xhr, status) {
                    myApp.alert('服务器错误', '', function () {
                        mainView.router.reloadPage('moviedetail');
                    });
                },
                complete: function (xhr, status) {
                }
            })
        }
    );

})
myApp.onPageReinit('morecomment', function (page) {

})

function getMovieSearchLibInfo(param) {
    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('正在加载请稍后...');
    $$.post('/moviesearchlib',
        param,
        function (data) {
            var data = JSON.parse(data);
            if (data.status === 'success') {
                setMovieSearchForm(data.data);
                if (data.data.length < 10) {
                    myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
                    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('已无更多影片');
                } else if (data.data.length == 10 && $$(mainView.activePage.container).find('.moviesearch').find('li').length == 10) {
                    myApp.attachInfiniteScroll($$(mainView.activePage.container).find('.moviesearch').parents('.page-content'));
                    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('上拉加载更多');
                } else {
                    $$(mainView.activePage.container).find('.movie-infinite-scroll-preloader div').text('上拉加载更多');
                }
            }
        });
}

function setMovieForm(MovieData) {
    // 生成新条目的HTML
    var html = '';
    $$.each(MovieData, function (i, v) {
        if (v["movie_name"]) {
            if (v["create_time"] && v["create_time"] != tempcreate_time) {
                tempcreate_time = v["create_time"];
                html += '<div style="padding-left: 15px;color: #9e9e9e">' + v["create_time"] + '</div>'
            }
            html += '<li>';
            html += '<a href="moviedetail?mid=' + v["mid"] + '" data-ignore-cache="true">';//暂留跳转
            html += '<div class="item-content">';

            html += '<div class="item-media"><img src="' + v["poster"] + '"  onerror=\"this.src=\'http://cdn.bestmovie.com.cn/wechat/img/movieNull.jpg\'\" width="90" height="120"></div>';
            html += '<div class="item-inner" style="margin-left: 15px">';
            html += '<div class="item-title-row">';
            html += '<div class="item-title">' + v["movie_name"] + '</div>';
            html += '<div class="item-after"><b style="color:red">' + v["score"] + '</b></div>';
            html += '</div>';
            html += '<div class="item-subtitle">';
            html += '<div class="overhide" style ="margin-top: 20px">导演:' + v["director"] + '</div>';
            html += '<div class="overhide">演员:' + v["cast"] + '</div>';
            html += '<div class="kinddiv row">';
            html += '<a href="#" class="kind col-35 movieType open-popover" data-popover=".popover-movieType" style="background-color: #03a9f4 ;max-width: 6em;display:-moz-inline-box;display:inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: center;border: none;color: white">' + v["category"] + '</a>';
            html += '<a href="#" class="kind col-35 movieType open-popover" data-popover=".popover-movieType" style="background-color: #8bc34a ;max-width: 6em;display:-moz-inline-box;display:inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: center;border: none;color: white">' + v["country"] + '</a>';
            html += '<a href="#" class="kind col-30 movieType open-popover" data-popover=".popover-movieType" style="background-color: #5856d6 ;max-width: 6em;display:-moz-inline-box;display:inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: center;border: none;color: white">' + v["publishdate"] + '</a>';
            html += '</div></div></div></div></a></li>';
        } else {
            html += '<li></li>';
        }

    });

    $$(mainView.activePage.container).find('.movie').append(html);
    loading = false;
    $$('.open-popover').on('click', function () {
        var clickedLink = this;
        var popoverHTML = '<div class="popover" style="width: 45%;height: 10%;text-align: center;">' +
            '<div class="content-block" style="margin-top:0px;">' +
            '<p style="margin: auto;margin-top: 16%">' + $$(this).text().replace(/\//g, ' ') + '</p>' +
            '</div>' +
            '</div>';
        myApp.popover(popoverHTML, clickedLink);
    });

}
function setMovieSearchForm(MovieData) {
    // 生成新条目的HTML
    var html = '';
    $$.each(MovieData, function (i, v) {
        html += '<li>';
        html += '<a href="moviesearchdetail?mid=' + v["mid"] + '" data-ignore-cache="true">';//暂留跳转
        // html += '<a href="moviesearchdetail?mid=' + v["mid"] + '&open_id=' + open_id + '" data-ignore-cache="true">';//暂留跳转
        html += '<div class="item-content">';
        html += '<div class="item-media"><img src="http://cdn.bestmovie.com.cn/MOVIE/' + v["mid"] + '/POSTER/' + v["mid"] + '.jpg' + '"  onerror=\"this.src=\'http://cdn.bestmovie.com.cn/wechat/img/movieNull.jpg\'\" width="90" height="120"></div>';
        html += '<div class="item-inner" style="margin-left: 15px">';
        html += '<div class="item-title-row">';
        html += '<div class="item-title">' + v["movie_name"] + '</div>';
        html += '<div class="item-after"><b style="color:red">' + v["score"] + '</b></div>';
        html += '</div>';
        html += '<div class="item-subtitle">';
        html += '<div class="overhide" style ="margin-top: 20px">导演:' + v["director"] + '</div>';
        html += '<div class="overhide">演员:' + v["cast"] + '</div>';
        html += '<div class="kinddiv row">';
        html += '<a href="#" class="kind col-35 movieType open-popover" data-popover=".popover-movieType" style="background-color: #03a9f4 ;max-width: 6em;display:-moz-inline-box;display:inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: center;border: none;color: white">' + v["category"] + '</a>';
        html += '<a href="#" class="kind col-35 movieType open-popover" data-popover=".popover-movieType" style="background-color: #8bc34a ;max-width: 6em;display:-moz-inline-box;display:inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: center;border: none;color: white">' + v["country"] + '</a>';
        html += '<a href="#" class="kind col-30 movieType open-popover" data-popover=".popover-movieType" style="background-color: #5856d6 ;max-width: 6em;display:-moz-inline-box;display:inline-block;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;text-align: center;border: none;color: white">' + v["publishdate"] + '</a>';
        html += '</div></div></div></div></a></li>';
    });

    $$(mainView.activePage.container).find('.moviesearch').append(html);
    loading = false;
    $$('.open-popover').on('click', function () {
        var clickedLink = this;
        var popoverHTML = '<div class="popover" style="width: 45%;height: 10%;text-align: center;">' +
            '<div class="content-block" style="margin-top:0px;">' +
            '<p style="margin: auto;margin-top: 16%">' + $$(this).text().replace(/\//g, ' ') + '</p>' +
            '</div>' +
            '</div>';
        myApp.popover(popoverHTML, clickedLink);
    });

}

var moviemySearchbar = null;
function findMovieLibByParam() {
    moviemySearchbar = myApp.searchbar('.cinemamoviesearchbar', {
        customSearch: true,
        onSearch: function () {
            myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.movie-infinite-scroll'));
            $$('.movie').html('');
            var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
            var _paramMovieType = [];
            for (var i = 0; i < chooseMovieTypeLength; i++) {
                _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
            }
            var param = {
                param_pageSize: $$(mainView.activePage.container).find('.movie').find('li').length,
                cinemaCode: $$(".movie").data('cinemaCode'),
                sort: $$('.content-block').eq(0).find('.buttonactive').data('sort'),
                movieType: JSON.stringify(_paramMovieType),
                movieCountry: $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
                movieYear: $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
                movieName: moviemySearchbar.query
            };
            getMovieInfomation(param);
        }
    });

};

var toolmoviemySearchbar = null;
function toolfindMovieLibByParam() {
    toolmoviemySearchbar = myApp.searchbar('.cinemamoviesearchbar-film', {
        customSearch: true,
        onSearch: function () {
            myApp.detachInfiniteScroll($$(mainView.activePage.container).find('.moviesearch-infinite-scroll'));
            $$(mainView.activePage.container).find('.movie').html('');
            var chooseMovieTypeLength = $$('.content-block').eq(1).find('.buttonactive').length;
            var _paramMovieType = [];
            for (var i = 0; i < chooseMovieTypeLength; i++) {
                _paramMovieType.push($$('.content-block').eq(1).find('.buttonactive').eq(i).dataset().movietype);
            }
            var param = {
                'param_pageSize': $$(mainView.activePage.container).find('.moviesearch').find('li').length,
                // param_pageSize: $$('.movie').find('li').length,
                indexCode: $$(".movie").data('indexCode'),
                sort: $$('.content-block').eq(0).find('.buttonactive').data('sort'),
                movieType: JSON.stringify(_paramMovieType),
                movieCountry: $$('.content-block').eq(2).find('.buttonactive').data('movieCountry'),
                movieYear: $$('.content-block').eq(3).find('.buttonactive').data('movieYear'),
                movieName: moviemySearchbar.query
            };
            getMovieSearchLibInfo(param);
        }
    });

}

/**
 * 更新 影吧片库 筛选条件
 * 右侧栏打开时
 */
function updataFilterByMovie() {

    $$('.content-block').find('.buttonactive').removeClass('buttonactive');
    if (!$$('.content-block').eq(0).find('button').hasClass('buttonactive')) {
        $$('.content-block').eq(0).find('.row .col-20 .button').eq(0).addClass('buttonactive');
    }
    if (!$$('.content-block').eq(3).find('button').hasClass('buttonactive')) {
        $$('.content-block').eq(3).find('.row .col-20 .button').eq(0).addClass('buttonactive');
    }
    $$.post('/moviefilter', function (data) {
        var data = JSON.parse(data);
        if (data.message === 'success') {
            // console.log(data.movieType);
            var Type = data.movieType;
            var Country = data.movieCountry;
            setMovieTypeFilter(Type);
            setMovieCountryFiler(Country);
        }
    });
}
function toolupdataFilterByMovie(page) {

    $$('.content-block').find('.buttonactive').removeClass('buttonactive');
    if (!$$('.content-block').eq(0).find('button').hasClass('buttonactive')) {
        $$('.content-block').eq(0).find('.row .col-20 .button').eq(0).addClass('buttonactive');
    }
    if (!$$('.content-block').eq(3).find('button').hasClass('buttonactive')) {
        $$('.content-block').eq(3).find('.row .col-20 .button').eq(0).addClass('buttonactive');
    }
    $$.post('/moviefilter', function (data) {
        var data = JSON.parse(data);
        if (data.message === 'success') {
            // console.log(data.movieType);
            var Type = data.movieType;
            var Country = data.movieCountry;
            setMovieTypeFilter(Type);
            setMovieCountryFiler(Country);


            var query = $$.parseUrlQuery(page.url);
            if (query && query.hasOwnProperty('pname')) {
                // var id = query.id;
                var pname = query.pname;

                var length = $$('.content-block  button').length;

                $$('.content-block button').each(function () {
                    // myApp.alert($$(this).text());
                    if ($$(this).text() === pname) {
                        // $$(this).addClass('buttonactive');
                        $$(this).click();
                        title(pname);
                    }

                })
                myApp.closePanel();
                // toolfindMovieLibByParam();
                // myApp.alert(length)
            }


        }
    });

}

function setMovieTypeFilter(Type) {
    $$('.content-block').eq(1).text('');
    var html = '';
    $$.each(Type, function (i, v) {
        if (( i + 1 ) % 5 == 1) {
            html += '<div class="row">';
        }
        html += '<div class="col-20">';
        if (i == 0) {
            html += '<button class="button buttonactive" data-movieType="0" style="max-width: 5em">' + v["movieType"] + '</button>';
        } else {
            html += '<button class="button" style="max-width: 5em" data-movieType="' + v["movieType"] + '">' + v["movieType"] + '</button>';
        }
        html += '</div>';
        if (( i + 1 ) % 5 == 0) {
            html += '</div>';
        }
    });
    if (!Type.length % 5 == 0) {
        var times = 5 - (Type.length % 5);
        for (var j = 0; j < times; j++) {
            html += '<div class="col-20"></div>';
        }
        html += '</div>';
    }
    $$('.content-block').eq(1).append(html);

    $$('.content-block').eq(1).find('.button').on('click', function () {

        if ($$(this).dataset().movietype == 0) {

            $$('.content-block').eq(1).find('.buttonactive').removeClass('buttonactive');

            if (!$$('.content-block').eq(1).find('.button').eq(0).hasClass('buttonactive')) {
                $$('.content-block').eq(1).find('.button').eq(0).addClass('buttonactive');
            }

        }

        if ($$(this).dataset().movietype != 0) {

            if ($$('.content-block').eq(1).find('.button').eq(0).hasClass('buttonactive')) {
                $$('.content-block').eq(1).find('.button').eq(0).removeClass('buttonactive');
            }

            $$(this).toggleClass('buttonactive');

        }
        if ($$('.content-block').eq(1).find('.buttonactive').length == 0) {
            $$('.content-block').eq(1).find('.button').eq(0).addClass('buttonactive');
        }

    });

}

function setMovieCountryFiler(Country) {
    $$('.content-block').eq(2).text('');
    var html = '';
    $$.each(Country, function (i, v) {
        if ((i + 1) % 5 == 1) {
            html += '<div class="row">';
        }
        html += '<div class="col-20">';
        if (i == 0) {
            html += '<button class="button buttonactive" data-movieCountry="0" style="max-width: 5em">' + v["movieCountry"] + '</button>';
        } else {
            html += '<button class="button" style="max-width: 5em" data-movieCountry="' + v["movieCountry"] + '">' + v["movieCountry"] + '</button>';
        }
        html += '</div>';
        if (( i + 1 ) % 5 == 0) {
            html += '</div>';
        }
    });
    if (!Country.length % 5 == 0) {
        var times = 5 - (Country.length % 5);
        for (var j = 0; j < times; j++) {
            html += '<div class="col-20"></div>';
        }
        html += '</div>';
    }
    $$('.content-block').eq(2).append(html);

    $$('.content-block').eq(2).find('.row .col-20 .button').on('click', function () {
        if (!$$(this).hasClass('buttonactive')) {
            $$('.content-block').eq(2).find('.buttonactive').removeClass('buttonactive');
            $$(this).addClass('buttonactive');
        }
    });
}

$$('.content-block').eq(0).find('.row .col-20 .button').on('click', function () {
    if (!$$(this).hasClass('buttonactive')) {
        $$('.content-block').eq(0).find('.buttonactive').removeClass('buttonactive');
        $$(this).addClass('buttonactive');
    }
});

$$('.content-block').eq(3).find('.row .col-20 .button').on('click', function () {
    if (!$$(this).hasClass('buttonactive')) {
        $$('.content-block').eq(3).find('.buttonactive').removeClass('buttonactive');
        $$(this).addClass('buttonactive');
    }
});

$$('.accordion-list').find('li').eq(4).find('.button').on('click', function () {
    myApp.closePanel('right');
});


/**
 * add by yan
 * 预约
 * @type {{}}
 */
myApp.onPageInit('cinemaroomtype', function (page) {

    var dataset = $$('.page[data-page="cinemaroomtype"]').dataset();

    $$('.booking-submit').on('click', function (e) {
        var formData = myApp.formToJSON('#booking-form');
        if (!formData.bookingDate) {
            myApp.alert('请选择观影日期!')
        } else if (!formData.startTime) {
            myApp.alert('请选择到店时间!')
        } else if (!formData.watchingMinutes) {
            myApp.alert('请选择观影时长')
        } else if (!formData.numbers) {
            myApp.alert('请选择观影人数')
        } else if (!formData.bookingContact) {
            myApp.alert('请填写联系人')
        } else if (!formData.bookingCode) {
            myApp.alert('请填写联系电话')
        } else {

            var zero = formData.bookingDate + ' ' + '00:00:00';
            var zeroTime = Date.parse(zero);
            var select = zeroTime + parseInt(pickerStartTime.cols[0].value)*60*60*1000 + parseInt(pickerStartTime.cols[2].value)*60*1000;
            var now = new Date().getTime();

            var phone = /^1[34578]\d{9}$/;

            if ((select-now) < 3*60*60*1000) {
                myApp.alert('只能预约三小时以后的场次！', '请重新选择到店时间！');
            } else if ( $$('#bookingContact').val().length > 30 ){
                myApp.alert('联系人输入过长！', '请重新填写联系人！');
            } else if ( !phone.test(formData.bookingCode)){
                myApp.alert('联系电话输入格式错误！', '请重新填写联系电话！');
            } else if ( $$('#userComment').val().length > 30 ){
                myApp.alert('留言输入过长！', '请重新填写留言！');
            } else {

                var message = '观影日期:' + formData.bookingDate + '\<br\>';
                message += '到店时间:' + formData.startTime + '\<br\>';
                message += '观影时长: ' + formData.watchingMinutes + '\<br\>';
                message += '联系人: ' + formData.bookingContact + '\<br\>';
                message += '联系电话: ' + formData.bookingCode + '\<br\>';

                myApp.confirm(message, '请确认您的预约信息', function () {

                    formData.cinemaCode = dataset.cinemaCode;
                    formData.roomtypeId = dataset.roomtypeId;
                    formData.startTime = pickerStartTime.cols[0].value + ':' + pickerStartTime.cols[2].value;
                    formData.watchingMinutes = pickerWatching.cols[0].value;
                    formData.numbers = pickerNumbers.cols[0].value;

                    $$.post('submitbooking', formData, function (data) {
                        data = JSON.parse(data);
                        if (data.errorMessage) {
                            myApp.alert(data.errorMessage, '预约失败！');
                        } else {
                            var success = '您的预约信息已提交！您可在个人信息中找到您的预约信息！\<br\>' +
                                '订单号： ' + data.booking_id;

                            myApp.alert(success, '预约成功！', function () {
                                mainView.back()
                            });
                        }
                    })
                });
            }

        }
    });

    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    var hours = now.getHours();
    if (month<10){
        month = '0'+month;
    }
    if (date<10){
        date = '0'+date;
    }

    //可预约开始时间
    var arg1 = parseInt(dataset.bookingStart.split(':')[0]);
    //可预约结束时间
    var arg2 = parseInt(dataset.bookingEnd.split(':')[0]);
    //结束超过超过凌晨处理
    if (arg2 < 12) {
        arg2 = arg2 + 24;
    }

    var pickerStartTime = myApp.picker({
        input: '#startTime',
        toolbarCloseText: '关闭',
        formatValue: function (p, values, displayValues) {
            return displayValues[0] + ':' + displayValues[1];
        },
        rotateEffect:true,
        cols: [
            {
                values: (function () {
                    var min = arg1;
                    var max = arg2;
                    if (arg1 < hours) {
                        min = hours + 1;
                    }

                    var arr = [];
                    for (var i = min; i <= max; i++) {
                        if (i < 10) {
                            arr.push('0' + i);
                        } else {
                            arr.push(i);
                        }
                    }
                    return arr;
                })(),
                displayValues: (function () {
                    var min = arg1;
                    var max = arg2;
                    if (arg1 < hours) {
                        min = hours + 1;
                    }
                    var arr = [];
                    for (var i = min; i <= max; i++) {
                        var hour = i;
                        if (hour >= 24) {
                            hour = i - 24;
                        }
                        if (hour < 10) {
                            arr.push('0' + hour);
                        } else {
                            arr.push(hour);
                        }
                    }
                    return arr;
                })()
            },
            {
                divider: true,
                content: ':'
            },
            {
                values: ['00', '15', '30', '45']
            }
        ]
    });

    var startTimezone = parseInt(dataset.startTimezone);
    var addTimezone = parseInt(dataset.addTimezone);
    var pickerWatching = myApp.picker({
        input: '#watchingMinutes',
        toolbarCloseText: '关闭',
        formatValue: function (p, values, displayValues) {
            return displayValues[0];
        },
        rotateEffect:true,
        cols: [
            {
                values: (function () {
                    var arr = [];
                    for (var i = startTimezone; i <= 600; i = i + addTimezone) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                displayValues: (function () {
                    var arr = [];
                    for (var i = startTimezone; i <= 600; i = i + addTimezone) {

                        var h = parseInt(i / 60);
                        var m = i % 60;
                        if (m < 10) {
                            m = '0' + m;
                        }
                        arr.push(h + '小时' + m + '分钟');
                    }
                    return arr;
                })()
            }
        ]
    });

    var peopleLimit = parseInt(dataset.peopleLimit);
    var pickerNumbers = myApp.picker({
        input: '#numbers',
        toolbarCloseText: '关闭',
        formatValue: function (p, values, displayValues) {
            return displayValues[0];
        },
        rotateEffect:true,
        cols: [
            {
                values: (function () {
                    var arr = [];
                    for (var i = 1; i <= peopleLimit; i++) {
                        arr.push(i);
                    }
                    return arr;
                })(),
                displayValues: (function () {
                    var arr = [];
                    for (var i = 1; i <= peopleLimit; i++) {
                        arr.push(i + '人');
                    }
                    return arr;
                })()

            }
        ]
    });


    $$('input[type="radio"]').on('change',function () {

        if (pickerStartTime.cols[0].displayValues){
            pickerStartTime.cols[0].displayValues = [];
        }
        if (pickerStartTime.cols[0].values){
            pickerStartTime.cols[0].values = [];
        }

        if (myApp.formToJSON('#booking-form').bookingDate == (year + '-'+month+'-'+date)){
            var min = arg1;
            var max = arg2;
            if (arg1 < hours) {
                min = hours + 1;
            }
            for (var i = min; i <= max; i++) {
                if (i < 10) {
                    pickerStartTime.cols[0].values.push('0' + i);
                } else {
                    pickerStartTime.cols[0].values.push(i);
                }
                var h = i;
                if (h >= 24) {
                    h = i - 24;
                }
                if (h >= 24) {
                    h = i - 24;
                }
                if (h < 10) {
                    pickerStartTime.cols[0].displayValues.push('0' + h);
                } else {
                    pickerStartTime.cols[0].displayValues.push(h);
                }
            }
        } else {
            var min = arg1;
            var max = arg2;
            for (var i = min; i <= max; i++) {
                if (i < 10) {
                    pickerStartTime.cols[0].values.push('0' + i);
                } else {
                    pickerStartTime.cols[0].values.push(i);
                }

                var hour = i;
                if (hour >= 24) {
                    hour = i - 24;
                }
                if (hour >= 24) {
                    hour = i - 24;
                }
                if (hour < 10) {
                    pickerStartTime.cols[0].displayValues.push('0' + hour);
                } else {
                    pickerStartTime.cols[0].displayValues.push(hour);
                }
            }
        }
    });

});
/**
 *  * add by yan
 * 订单
 * @type {{}}
 */
myApp.onPageInit('bookingorders', function (page) {

    // var dataset = $$('.page[data-page="bookingorders"]').dataset();
    // if (dataset.signPkg != undefined) {
    //     wx.config({
    //         debug: false,
    //         appId: dataset.appId,
    //         timestamp: dataset.timestamp,
    //         nonceStr: dataset.nonceStr,
    //         signature: dataset.signature,
    //         jsApiList: [
    //             'checkJsApi',
    //             'hideMenuItems',
    //             'onMenuShareTimeline',
    //             'onMenuShareAppMessage',
    //             'onMenuShareQQ',
    //             'onMenuShareWeibo',
    //             'onMenuShareQZone',
    //             'getNetworkType',
    //             'scanQRCode',
    //             'openLocation',
    //             'getLocation'
    //         ]
    //     });
    // }

    var items1 = [];
    var items2 = [];
    var items3 = [];
    var list1 = myApp.virtualList($$('#tab1 .virtual-list'), {
        items: items1,
        template: '<li class="card facebook-card" data-booking-id="{{this.booking_id}}">' +
        '<div class="card-header no-border">' +
        '   <div class="facebook-name">{{this.cinema_name}}</div>' +
        '   <div class="facebook-date">{{this.createtime}}</div>' +
        '</div>' +
        '<div class="card-content">' +
        '   <div class="card-content-inner">' +
        '       <p>影厅：{{this.roomtype_name}}</p>' +
        '       <p>日期：{{this.booking_date}} ({{formatChineseWeek this.week_day}})</p>' +
        '       <p>时间：{{this.start_time}} - {{this.end_time}}</p>' +
        // '       <p>人数：{{jsonDecodeNumbers this.user_comment}}</p>' +
        // '       <p>联系人：{{jsonDecodeContact this.user_comment}}</p>' +
        '       <p class="color-gray">备注：{{this.user_comment}}</p>' +
        '   </div>' +
        '</div>' +
        '<div class="card-footer">' +
        '   <span>订单号:{{this.order_code}}</span><span></span><span></span><span></span><span></span>' +
        '   <span></span>' +
        // '   <a href="#" class="link share-booking-{{this.booking_id}}" data-booking-id="{{this.booking_id}}">分享</a>' +
        '   <a href="#" class="link cancel-booking-{{this.booking_id}}" data-booking-id="{{this.booking_id}}">取消</a>' +
        '</div>' +
        '</li>',
        height: 259
    });

    var list2 = myApp.virtualList($$('#tab2 .virtual-list'), {
        items: items2,
        template: '<li class="card facebook-card" data-booking-id="{{this.booking_id}}">' +
        '<div class="card-header no-border">' +
        '   <div class="facebook-name">{{this.cinema_name}}</div>' +
        '   <div class="facebook-date">{{this.createtime}}</div>' +
        '</div>' +
        '<div class="card-content">' +
        '   <div class="card-content-inner">' +
        '       <p>影厅：{{this.roomtype_name}}</p>' +
        '       <p>日期：{{this.booking_date}} ({{formatChineseWeek this.week_day}})</p>' +
        '       <p>时间：{{this.start_time}} - {{this.end_time}}</p>' +
        // '       <p>人数：{{jsonDecodeNumbers this.user_comment}}</p>' +
        // '       <p>联系人：{{jsonDecodeContact this.user_comment}}</p>' +
        '       <p class="color-gray">备注：{{this.user_comment}}</p>' +
        '   </div>' +
        '</div>' +
        '<div class="card-footer">' +
        '   <span>订单号:{{this.order_code}}</span><span></span><span></span><span></span><span></span>' +
        '   <span></span>' +
        // '   <a href="#" class="link share-booking-{{this.booking_id}}" data-booking-id="{{this.booking_id}}">分享</a>' +
        '   <span></span>' +
        '</div>' +
        '</li>',
        height: 259
    });

    var list3 = myApp.virtualList($$('#tab3 .virtual-list'), {
        items: items3,
        template: '<li class="card facebook-card" data-booking-id="{{this.booking_id}}">' +
        '<div class="card-header no-border">' +
        '   <div class="facebook-name">{{this.cinema_name}}</div>' +
        '   <div class="facebook-date">{{this.createtime}}</div>' +
        '</div>' +
        '<div class="card-content">' +
        '   <div class="card-content-inner">' +
        '       <p>影厅：{{this.roomtype_name}}</p>' +
        '       <p>日期：{{this.booking_date}} ({{formatChineseWeek this.week_day}})</p>' +
        '       <p>时间：{{this.start_time}} - {{this.end_time}}</p>' +
        // '       <p>人数：{{jsonDecodeNumbers this.user_comment}}</p>' +
        // '       <p>联系人：{{jsonDecodeContact this.user_comment}}</p>' +
        '       <p class="color-gray">备注：{{this.user_comment}}</p>' +
        '   </div>' +
        '</div>' +
        '<div class="card-footer">' +
        '   <span>订单号:{{this.order_code}}</span><span></span><span></span><span></span><span></span>' +
        '   <span>已取消</span>' +
        '   <span></span>' +
        '</div>' +
        '</li>',
        height: 259
    });

    var req = {
        state: 1,
        page1: 0,
        page2: 0,
        page3: 0,
    };

    $$('#tab1').on('show', function () {

        req.state = 1;
        if (req.page1 == 0) {
            $$.post('getbookingorders', req, function (data) {
                data = JSON.parse(data);
                if (data.errorMessage) {
                    myApp.detachInfiniteScroll($$('#tab1 .infinite-scroll'));
                    $$('#tab1 .infinite-scroll-preloader').remove();
                } else {
                    if (data.isLast) {
                        myApp.detachInfiniteScroll($$('#tab1 .infinite-scroll'));
                        $$('#tab1 .infinite-scroll-preloader').remove();
                    }

                    for (var i=0; i<data.orders.length;i++){
                        list1.appendItem(data.orders[i]);
                        bindCancelBooking(list1,data.orders[i].booking_id);
                        // bindShareBooking(list1,data.orders[i].booking_id);
                    }
                    req.page1++;
                }
            })
        }

        var loading = false;
        $$('#tab1.infinite-scroll').on('infinite', function (e) {
            if (loading) return;
            loading = true;
            $$.post('getbookingorders', req, function (data) {
                data = JSON.parse(data);
                if (data.errorMessage) {

                    myApp.detachInfiniteScroll($$('#tab1.infinite-scroll'));
                    $$('#tab1 .infinite-scroll-preloader').remove();
                } else {
                    if (data.isLast) {
                        myApp.detachInfiniteScroll($$('#tab1.infinite-scroll'));
                        $$('#tab1 .infinite-scroll-preloader').remove();
                    }
                    for (var i=0; i<data.orders.length;i++){
                        list1.appendItem(data.orders[i]);
                        bindCancelBooking(list1,data.orders[i].booking_id);
                        // bindShareBooking(list1,data.orders[i].booking_id);
                    }
                    req.page1++;
                }
                loading = false;
            })
        })


    });

    $$('#tab2').on('show', function () {
        req.state = 2;
        if (req.page2 == 0) {
            $$.post('getbookingorders', req, function (data) {
                data = JSON.parse(data);
                if (data.errorMessage) {
                    myApp.detachInfiniteScroll($$('#tab2 .infinite-scroll'));
                    $$('#tab2 .infinite-scroll-preloader').remove();
                } else {
                    if (data.isLast) {
                        myApp.detachInfiniteScroll($$('#tab2 .infinite-scroll'));
                        $$('#tab2 .infinite-scroll-preloader').remove();
                    }
                    for (var i=0; i<data.orders.length;i++){
                        list2.appendItem(data.orders[i]);
                        // bindShareBooking(list2,data.orders[i].booking_id);
                    }
                    req.page2++;
                }
            })
        }

        var loading = false;
        $$('#tab2.infinite-scroll').on('infinite', function (e) {
            if (loading) return;
            loading = true;
            $$.post('getbookingorders', req, function (data) {
                data = JSON.parse(data);
                if (data.errorMessage) {
                    myApp.detachInfiniteScroll($$('#tab2.infinite-scroll'));
                    $$('#tab2 .infinite-scroll-preloader').remove();
                } else {
                    if (data.isLast) {
                        myApp.detachInfiniteScroll($$('#tab2.infinite-scroll'));
                        $$('#tab2 .infinite-scroll-preloader').remove();
                    }
                    for (var i=0; i<data.orders.length;i++){
                        list2.appendItem(data.orders[i]);
                        // bindShareBooking(list2,data.orders[i].booking_id);
                    }
                    req.page2++;
                }
                loading = false;
            })
        })
    });

    $$('#tab3').on('show', function () {
        req.state = 3;
        if (req.page3 == 0) {
            $$.post('getbookingorders', req, function (data) {
                data = JSON.parse(data);
                if (data.errorMessage) {
                    myApp.detachInfiniteScroll($$('#tab3 .infinite-scroll'));
                    $$('#tab3 .infinite-scroll-preloader').remove();
                } else {
                    if (data.isLast) {
                        myApp.detachInfiniteScroll($$('#tab3 .infinite-scroll'));
                        $$('#tab3 .infinite-scroll-preloader').remove();
                    }
                    list3.appendItems(data.orders);
                    req.page3++;
                }
            })
        }

        var loading = false;
        $$('#tab3.infinite-scroll').on('infinite', function (e) {
            if (loading) return;
            loading = true;
            $$.post('getbookingorders', req, function (data) {
                data = JSON.parse(data);
                if (data.errorMessage) {
                    myApp.detachInfiniteScroll($$('#tab3.infinite-scroll'));
                    $$('#tab3 .infinite-scroll-preloader').remove();
                } else {
                    if (data.isLast) {
                        myApp.detachInfiniteScroll($$('#tab3.infinite-scroll'));
                        $$('#tab3 .infinite-scroll-preloader').remove();
                    }
                    list3.appendItems(data.orders);
                    req.page3++;
                }
                loading = false;
            })
        })
    });
    myApp.showTab('#tab1');

    function bindShareBooking(list,id) {

        // 发送给朋友: "menuItem:share:appMessage"
        // 分享到朋友圈: "menuItem:share:timeline"
        // 分享到QQ: "menuItem:share:qq"
        // 分享到Weibo: "menuItem:share:weiboApp"

        // wx.checkJsApi({
        //     jsApiList: ['showOptionMenu','onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareQZone'],
        //     success: function(res) {
        //         console.log(res);
        //         // 以键值对的形式返回，可用的api值true，不可用为false
        //         // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
        //     }
        // });

        $$('.share-booking-'+ id).on('click', function (event) {
            var obj = {};
            for (var i = 0; i < list.items.length; i++) {
                if (id == list.items[i].booking_id) {
                    obj.title = '预约分享';
                    obj.desc = '影厅：' + list.items[i].roomtype_name +
                        '日期：' + list.items[i].booking_date +
                        '时间：' + list.items[i].start_time + '-' + list.items[i].end_time;
                    obj.link = 'http://www.xxbiquge.com/3_3496/3257093.html';
                    obj.imgUrl = list.items[i].roomtype_pic;
                    obj.success = function () {

                    };
                    obj.cancel = function () {

                    };

                    // var opt = {
                    //     title: '预约分享', // 分享标题
                    //     desc: '影厅：' + list.items[i].roomtype_name + '日期：' + list.items[i].booking_date + '时间：' + list.items[i].start_time + '-' + list.items[i].end_time,//分享描述
                    //     link: 'www.baidu.com', // 分享链接
                    //     imgUrl: list.items[i].roomtype_pic, // 分享图标
                    //     success: function () {
                    //     },
                    //     cancel: function (res) {
                    //     }
                    // };

                    break;
                }
            }
            wx.onMenuShareTimeline(obj);
        });
    }

    function bindCancelBooking(list,id) {

        $$('.cancel-booking-'+ id).on('click', function (event) {

            var e = '是否取消该订单？';
            var a = '请确认！';
            var req = $$(this).dataset();
            var index = -1;
            for (var i = 0; i < list.items.length; i++) {
                if (req.bookingId == list.items[i].booking_id) {
                    index = i;
                    break;
                }
            }

            myApp.confirm(e, a, function () {
                $$.post('cancelbooking', req, function (data) {
                    data = JSON.parse(data);
                    if (data.errorMessage) {
                        myApp.alert(data.errorMessage, '取消失败！');
                        return;
                    }
                    myApp.alert('您已成功取消订单！', '取消成功！', function () {
                        list.deleteItem(index);
                    });
                })
            }, function () {
            });
        });
    }

});

myApp.init();
routerInit();




